package com.hckjsec.oa.controller;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.hckjsec.common.general.MapLongNameView;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.SecurityUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.oa.domain.OaDate;
import com.hckjsec.oa.domain.OaView.*;
import com.hckjsec.oa.service.IOaDateService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.oa.domain.OaAttendance;
import com.hckjsec.oa.service.IOaAttendanceService;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 公司OA考勤Controller
 * 
 * @author cyt
 * @date 2021-12-27
 */
@RestController
@RequestMapping("/oa/attendance")
public class OaAttendanceController extends BaseController
{
    public static Map<String,String> stateHt = new Hashtable<String,String>();
    static {
        if(stateHt.size()==0){
            stateHt.put("-1","旷工");
            stateHt.put("0","正常");
            stateHt.put("1","迟到");
            stateHt.put("2","早退");
        }
    }
    @Autowired
    private IOaAttendanceService oaAttendanceService;
    @Autowired
    private IOaDateService oaDateService;

    /**
     * 查询公司OA考勤列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OaAttendance oaAttendance)
    {
        startPage();
        List<OaAttendance> list = oaAttendanceService.selectOaAttendanceList(oaAttendance);
        return getDataTable(list);
    }

    /**
     * 导出公司OA考勤列表
     */
    @Log(title = "公司OA考勤", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OaAttendance oaAttendance)
    {
        List<OaAttendance> list = oaAttendanceService.selectOaAttendanceList(oaAttendance);
        ExcelUtil<OaAttendance> util = new ExcelUtil<OaAttendance>(OaAttendance.class);
        return util.exportExcel(list, "attendance");
    }

    /**
     * 获取公司OA考勤详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(oaAttendanceService.selectOaAttendanceById(id));
    }



    /**
     * 我的考勤
     * @author cyt
     * @date 2021-06-23
     */
    @PostMapping(value = "/getMyAttendance")
    public AjaxResult getMyAttendance(@RequestBody OaAttendance oaAttendance) {
        FinalSignView finalSignView = new  FinalSignView();
        Long  userId = SecurityUtils.getUserId();
        String   startTime =  oaAttendance.getYearMonth()+"-01";
        String   endTim = DateUtils.getLastday(oaAttendance.getYearMonth().split("-")[0],oaAttendance.getYearMonth().split("-")[1]);
        if (endTim.substring(0,7).equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM,DateUtils.getNowDate()))){
            endTim =   DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getNowDate());//当前时间
        }else{
           if (DateUtils.compareStrDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM,DateUtils.getNowDate()),endTim.substring(0,7),DateUtils.YYYY_MM)){//下个月
               endTim =   DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getNowDate());//当前时间
           }
        }
        //查询员工入职时间
        if (StringUtils.isNotNull(SecurityUtils.getSysUser().getInductionDate())){
            String rzDate = StringUtils.isHcNull(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,SecurityUtils.getSysUser().getInductionDate()), "");
            if (DateUtils.compareStrDate(endTim,rzDate,DateUtils.YYYY_MM_DD)){
                return AjaxResult.success(finalSignView);
            }
            if (DateUtils.compareStrDate(startTime,rzDate,DateUtils.YYYY_MM_DD)){
                startTime = rzDate;
            }
        }
        OaDate oaDate = new  OaDate();
        oaDate.setBeginTime(startTime);
        oaDate.setEndTime(endTim);
        List<OaDate> oaDateList = oaDateService.selectOaDateList(oaDate);
        LinkedHashMap<String, HomeSignView> calendarMap = new LinkedHashMap<>();
        oaDateList.forEach(kv->{
            HomeSplitView signIn = new HomeSplitView("0");
            HomeSplitView signOut = new HomeSplitView("1");
            Long festival = kv.getFestival();
            HomeSignView homeSignView = new HomeSignView();
            homeSignView.setDate(kv.getDate());
            if (festival == 0){//代表需要上班
                signIn.setState("-1");
                signOut.setState("-1");
            }else{
                signIn.setState("0");
                signOut.setState("0");
            }
            homeSignView.setFestival(festival);
            homeSignView.setSignIn(signIn);
            homeSignView.setSignOut(signOut);
            String   date =  DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,kv.getDate());
            calendarMap.put(date,homeSignView);
        });
        OaAttendance findOaAttendance = new  OaAttendance();
        findOaAttendance.setBeginTime(startTime);
        findOaAttendance.setEndTime(endTim);
        findOaAttendance.setUserId(userId);
        List<OaAttendance> oaAttendanceList =  oaAttendanceService.selectOaAttendanceList(findOaAttendance);
        oaAttendanceList.forEach(kv->{
            String   date =  DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,kv.getDate());
            HomeSignView homeSignView = calendarMap.get(date);
            String period = kv.getPeriod();
            if ("0".equals(period)){//签到
                HomeSplitView oldSignIn = homeSignView.getSignIn();
                oldSignIn.setState(kv.getState());
                oldSignIn.setPthTime(kv.getPthTime());
                homeSignView.setSignIn(oldSignIn);
            }else if ("1".equals(period)) {//签退
                HomeSplitView oldSignOut = homeSignView.getSignOut();
                oldSignOut.setState(kv.getState());
                oldSignOut.setPthTime(kv.getPthTime());
                homeSignView.setSignOut(oldSignOut);
            }
            calendarMap.put(date,homeSignView);
        });
        List<HomeFinalSignView>  findList = new ArrayList<>();
        List<String>  pieList = new ArrayList<>();
        List<Double> inList = new ArrayList<>();
        List<Double> outList = new ArrayList<>();
        List<String>  dateList = new ArrayList<>();
        calendarMap.forEach((k,v)->{
            HomeFinalSignView homeFinalSignView = new HomeFinalSignView();
            homeFinalSignView.setDate(v.getDate());
            List<HomeSplitView> checkState = new ArrayList<>();
            checkState.add(v.getSignIn());
            checkState.add(v.getSignOut());
            homeFinalSignView.setCheckState(checkState);
            Long festival = v.getFestival();
            if (festival == 0){
                dateList.add(DateUtils.parseDateToStr(DateUtils.MM_DD,v.getDate()));
                if (StringUtils.isNotNull(v.getSignIn().getPthTime())){
                    String inStr = DateUtils.parseDateToStr(DateUtils.HH_MM,v.getSignIn().getPthTime());
                    String frontStr = inStr.split(":")[0];
                    String afterStr = inStr.split(":")[1];
                    int afterInt = Integer.parseInt(afterStr)*100/60;
                    frontStr = frontStr+"."+afterInt;
                    inList.add(Double.valueOf(frontStr));
                }else{
                    inList.add(0.0);
                }
                if (StringUtils.isNotNull(v.getSignOut().getPthTime())){
                    String outStr = DateUtils.parseDateToStr(DateUtils.HH_MM,v.getSignOut().getPthTime());
                    String frontStr = outStr.split(":")[0];
                    String afterStr = outStr.split(":")[1];
                    int afterInt = Integer.parseInt(afterStr)*100/60;
                    frontStr = frontStr+"."+afterInt;
                    outList.add(Double.valueOf(frontStr));
                }else{
                    outList.add(0.0);
                }
                pieList.add(v.getSignIn().getState());
                pieList.add(v.getSignOut().getState());
                findList.add(homeFinalSignView);
            }else{
                //判断下  如果是周六周日和法定节假日   如果没打开  就过滤
                boolean isDk = false;
                if (StringUtils.isNotNull(v.getSignIn().getPthTime()) ||  StringUtils.isNotNull(v.getSignOut().getPthTime())){
                    isDk = true;
                }
                if (isDk){
                    dateList.add(DateUtils.parseDateToStr(DateUtils.MM_DD,v.getDate()));
                    if (StringUtils.isNotNull(v.getSignIn().getPthTime())){
                        String inStr = DateUtils.parseDateToStr(DateUtils.HH_MM,v.getSignIn().getPthTime());
                        String frontStr = inStr.split(":")[0];
                        String afterStr = inStr.split(":")[1];
                        int afterInt = Integer.parseInt(afterStr)*100/60;
                        frontStr = frontStr+"."+afterInt;
                        inList.add(Double.valueOf(frontStr));
                    }else{
                        inList.add(0.0);
                    }
                    if (StringUtils.isNotNull(v.getSignOut().getPthTime())){
                        String outStr = DateUtils.parseDateToStr(DateUtils.HH_MM,v.getSignOut().getPthTime());
                        String frontStr = outStr.split(":")[0];
                        String afterStr = outStr.split(":")[1];
                        int afterInt = Integer.parseInt(afterStr)*100/60;
                        frontStr = frontStr+"."+afterInt;
                        outList.add(Double.valueOf(frontStr));
                    }else{
                        outList.add(0.0);
                    }
                    pieList.add(v.getSignIn().getState());
                    pieList.add(v.getSignOut().getState());
                    findList.add(homeFinalSignView);
                }
            }
        });
        finalSignView.setList(findList);
        Map<String,Long> collect = pieList.stream().collect(Collectors.groupingBy(
                Function.identity(), Collectors.counting()
        ));
        List<MapLongNameView> piedata = new ArrayList<>();
        collect.forEach((k,v)->{
            piedata.add(new MapLongNameView(stateHt.get(k),v));
        });
        finalSignView.setPiedata(piedata);
        List<HomeLineView> homeLineViewList = new ArrayList<>();
        HomeLineView inHomeLineView = new HomeLineView();
        inHomeLineView.setName("上班");
        inHomeLineView.setType("line");
        inHomeLineView.setSmooth(true);
        inHomeLineView.setData(inList.toArray(new Double[inList.size()]));
        homeLineViewList.add(inHomeLineView);
        HomeLineView outHomeLineView = new HomeLineView();
        outHomeLineView.setName("下班");
        outHomeLineView.setType("line");
        outHomeLineView.setSmooth(true);
        outHomeLineView.setData(outList.toArray(new Double[outList.size()]));
        homeLineViewList.add(outHomeLineView);
        finalSignView.setLinedata(homeLineViewList);
        finalSignView.setWorkdate(dateList.toArray(new String[dateList.size()]));
        return AjaxResult.success(finalSignView);
    }

}
